<template>
	<view>
		<!-- <view class="cu-bar bg-black">
			<view class="action" @tap="BackPage">
				<text class="cuIcon-back text-gray"></text>
			</view>
			 
			<view class="action text-bold" @tap="showModal('RadioModal')">
				{{title}}
			</view>
			<view class="action">
				 
			</view>
		</view> -->

		<view class="cu-modal" :class="modalName=='RadioModal'?'show':''" @tap="hideModal">
			<view class="cu-dialog" @tap.stop="">
				<radio-group class="block" @change="RadioChange2">
					<view class="cu-list menu text-left">
						<view class="cu-item" v-for="(item,index) in marketList" :key="index">
							<label class="flex justify-between align-center">
								<view class=" ">{{item.name+'/'+item.priceUnit}}</view>
								<radio class="round" style="right: 13px; position: fixed;" :class="radio2== index?'checked':''" :checked="radio2== index?true:false"
								 :value="index+''"></radio>
							</label>
						</view>
					</view>
				</radio-group>
			</view>
		</view>

		<view class="flex bg-white">
			<!-- <view class="flex-sub padding-sm radius">
				<text :class="buyfrom.sim==1 ? 'iconfont icon-jinbi text-green' : 'iconfont icon-jifenduihuan text-pink' " style="font-size: xx-large;"></text>
				<text class="text-xl">{{tradename[buyfrom.sim]}}</text>
			</view> -->
			<view class="flex-sub   padding-sm   radius">
				<view class="uni-h2" :class="change > 0 ? 'text-green' : 'text-red'">
					{{close}}
				</view>
				<view class="toptext" :class="change > 0 ? 'text-green' : 'text-red'">
					≈{{cnyprice}}CNY {{change > 0 ? '+' : ''}}{{change}}%
				</view>
				<!-- <view class="toptext">
					≈{{cnyprice}}CNY
				</view> -->
				<!-- <view class="toptext">
					≈{{usdprice}}USD
				</view> -->
			</view>
			<view class="flex-sub   padding-sm radius ">
				<view class="flex " style="position: inherit;">
					<view class="flex-sub  radius ">
						<view class="tit2 ">{{i18n.kline.high}}</view>
						<text class="tit ">{{high}}</text>
					</view>
					<view class="flex-sub  radius ">
						<view class="tit2 ">{{i18n.order.turnover}}(USDT)</view>
						<text class="tit ">{{volume}}</text>
					</view>
				</view>
				<view class="flex margin-top-sm" style="position: inherit;">
					<view class="flex-sub  radius ">
						<view class="tit2 ">{{i18n.kline.low}}</view>
						<text class="tit ">{{low}}</text>
					</view>
					<view class="flex-sub  radius ">
						<view class="tit2 ">{{i18n.order.volume}}({{salename}})</view>
						<text class="tit ">{{amount}}</text>
					</view>

				</view>

			</view>
		</view>

		<view class="chart">
			<scroll-view scroll-x class="bg-white nav">
				<view class="flex text-center">
					<view class="cu-item flex-sub" :class="item.id==TabCur?'text-yellow':''" v-for="(item,index) in tabList" :key="index"
					 @tap="tabSelect(item)">
						{{item.name}}
					</view>
				</view>
			</scroll-view>
			<view class="set-box" v-show="setPop">
				<view class="item u-flex">
					<view class="left u-flex">
						<view class="title u-flex-1">主图</view>
						<scroll-view scroll-x>
							<view>
								<text :class="zhibiao=='BOLL'?'active':''" @tap="setb('BOLL')">BOLL</text>
								<text :class="zhibiao=='5MA'?'active':''" @tap="setb('5MA')">5MA</text>
								<text :class="zhibiao=='10MA'?'active':''" @tap="setb('10MA')">10MA</text>
								<text :class="zhibiao=='20MA'?'active':''" @tap="setb('20MA')">20MA</text>
							</view>
						</scroll-view>
					</view>
					<view class="right" @tap="hideb">隐藏</view>
				</view>
				<view class="item u-flex">
					<view class="left u-flex">
						<view class="title u-flex-1">副图</view>
						<scroll-view scroll-x>
							<view>
								<text :class="zhibiao=='MACD'?'active':''" @tap="setb('MACD')">MACD</text>
								<text :class="zhibiao=='RSI'?'active':''" @tap="setb('RSI')">RSI</text>
							</view>
						</scroll-view>
					</view>
				</view>
			</view>
			<view id="trade-view"></view>
		</view>

		<!-- <form>
			<view class="cu-form-group">
				<view class="title">{{i18n.kline.Principal}}</view>
				<view class="inin">
					<input type="number" :placeholder="i18n.kline.inputmoney+userinfo.wall1" v-model="buyfrom.hand"></input>
				</view>
				<view>USDT</view>
			</view>
			<radio-group class="block" @change="RadioChange">
				<view class="cu-form-group">
					<view class="title">{{i18n.kline.time}}</view>
					<view>
						<template v-for="(item,index) in myconfig.qx_time">
							<radio class=' margin-left' :class="radio==index?'checked':''" :checked="radio==index?true:false" :value="index"></radio>{{item}}{{i18n.kline.minutes}}
						</template>
					</view>
				</view>
			</radio-group>
		</form> -->

		<view class="cu-list grid col-2 no-border ">
			<view class="cu-item">
				<button class="cu-btn bg-green dbt" @tap="onClick('1')">{{i18n.kline.BuyUp}}</button>
			</view>
			<view class="cu-item">
				<button class="cu-btn bg-red dbt" @tap="onClick('2')">{{i18n.kline.BuyDown}}</button>
			</view>

		</view>

		<!-- 委托 -->
		<!-- <qiOrderList :salename="salename" :buyname="buyname" ref="child"></qiOrderList> -->
		<ktabs :salename="salename" :close="close"></ktabs>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	// import {
	// 	widget as TvWidget
	// } from '@/static/tradeview/charting_library/charting_library.min.js';
	import {
		widget as TvWidget
	} from '@/static/charting_library/charting_library.min.js';

	import {
		feed
	} from '@/kline/datafeeds/datafees.js';
	import socket from '@/kline/datafeeds/socket.js';
	import Event from '@/kline/datafeeds/event.js'
	import qiOrderList from '@/components/qiOrderList.vue'
	import ktabs from '@/components/ktabs.vue'
	export default {
		components: {
			qiOrderList,
			ktabs
		},
		data() {
			return {
				title: '',
				buyfrom: {
					price: 0,
					hand: '', //本金
					sim: '1', //1 实盘 2 模拟
					product_id: 'BTC',
					rise_fall: '1', // 1 买涨 2 买跌
				},
				// tradename: ['1', '普通场', '包赔场'],
				widget: null,
				datafeeds: new feed(),
				symbol: null,
				interval: null,
				cacheData: {},
				lastTime: null,
				getBarTimer: null,
				isLoading: true,
				buyname: '--',
				salename: '--',
				open: '--',
				high: '--',
				low: '--',
				close:1,
				volume: '--',
				amount: '--', //成交量
				id: 0,
				change: 0,
				TabCur: 0,
				scrollLeft: 0,
				// tabList: [

				// 	{
				// 		name: '1分钟',
				// 		id: '0',
				// 		time: '1'
				// 	},
				// 	{
				// 		name: '5分钟',
				// 		id: '1',
				// 		time: '5'
				// 	},
				// 	{
				// 		name: '30分钟',
				// 		id: '2',
				// 		time: '30'
				// 	},
				// 	{
				// 		name: '1小时',
				// 		id: '3',
				// 		time: '60'
				// 	},
				// 	{
				// 		name: '4小时',
				// 		id: '4',
				// 		time: '240'
				// 	},
				// 	{
				// 		name: '日线',
				// 		id: '5',
				// 		time: '1D'
				// 	},

				// ],
				radio: '1', //表单选择
				date: new Date().Format('h:m:s'),
				modalName: null,
				radio2: '',
				marketList: {},
				
				setPop: false,
				zhibiao: '',
				
			};
		},
		onNavigationBarButtonTap(e) {
			console.log(e.index)
			if (e.index == 0) {
				this.showModal('RadioModal')
			}
			if (e.index == 1) {
				this.buyfrom.sim = this.buyfrom.sim == 1 ? '2' : '1';

			}
		},
		computed: {
			...mapState({
				userinfo: state => state.user.userinfo,
				myconfig: state => state.user.myconfig
			}),
			cnyprice() {
				return Math.round(this.close * this.myconfig.rate_cny2usdt * 100) / 100;
			},
			usdprice() {
				return Math.round(this.close * this.myconfig.rate_usdt2usd * 100) / 100;
			},
			hasLogin() {
				return this.userinfo.id ? true : false
			},
			i18n() {
				return this.$t('message');
			},
			tabList() {
				return [
					{
							name: '设置',
							id: '666',
							time: '1D'
						},
					{
						name: this.i18n.kline.m1,
						id: '0',
						time: '1'
					},
					{
						name: this.i18n.kline.m5,
						id: '1',
						time: '5'
					},
					{
						name: this.i18n.kline.m30,
						id: '2',
						time: '30'
					},
					{
						name: this.i18n.kline.m60,
						id: '3',
						time: '60'
					},
					{
						name: this.i18n.kline.m240,
						id: '4',
						time: '240'
					},
					{
						name: this.i18n.kline.d1,
						id: '5',
						time: '1D'
					},

				];
			},
			tradename() {
				return ['1', this.i18n.kline.room2, this.i18n.kline.room1];
			}
		},
		onLoad(option) {


			let data = {}
			data = option.data ? JSON.parse(option.data) : {};
			this.symbol = data.symbol ? data.symbol : 'btcusdt';
			this.salename = data.name ? data.name : 'BTC';
			this.buyname = data.priceUnit ? data.priceUnit : 'USDT';
			this.buyfrom.sim = data.type ? data.type : '2'

			// this.title = data.name + '/' + data.priceUnit + '▼';
			this.title = data.name + '/' + data.priceUnit;
			uni.setNavigationBarTitle({
				title: this.title
			});
			this.buyfrom.product_id = data.name;
			this.marketList = uni.getStorageSync('marketList');

		},
		onShow() {
			console.log('show----------')
			if (!this.hasLogin) {
				uni.navigateTo({
					url: '/pages/public/login'
				})
				return 1;
			}
			this.getUserinfo();
			if (this.$timer.length > 0) {
				for (let i = 0; i < this.$timer.length; i++) {
					clearInterval(this.$timer[i])
				}
			}

			// setTimeout(() => {
			this.$timer.push(setInterval((e) => {
				this.date = new Date().Format('h:m:s');
				console.log(this.date)
			}, 1000))
			// }, 3000)
			// this.$timer.push(setInterval((e) => { 
			// 	this.ttt(); 
			// }, 500))
		},
		// onBackPress() {
		// 	console.log(1111111)
		// 	clearInterval(this.Timer);
		// },
		destroyed() {
			console.log('kline-----------destroyed')

			socket.close();
			// clearInterval(this.Timer);
			if (this.$timer.length > 0) {
				for (let i = 0; i < this.$timer.length; i++) {
					clearInterval(this.$timer[i])
				}
			}
		},

		mounted() {
			this.init('1');
		},
		methods: {
			...mapActions(['getUserinfo']),
			Timer() {},
			init(interval = 1) {
				// if (!this.widget) {
				this.widget = new TvWidget({
					symbol: this.symbol,
					interval: interval,
					autosize: true,
					fullscreen: false,
					container_id: 'trade-view',
					datafeed: this.datafeeds,
					library_path: '/static/charting_library/',
					timezone: 'Asia/Shanghai',
					locale: 'en', //zh en
					debug: true,
					//设置默认不显示组件
					disabled_features: [
						// 'header_symbol_search',
						// 'symbol_search_hot_key',
						'volume_force_overlay',
						// 'header_interval_dialog_button',
						// 'show_interval_dialog_on_key_press',
						// 'legend_context_menu',
						// 'control_bar',
						// 'edit_buttons_in_legend',
						// 'dont_show_boolean_study_arguments',
						// 'header_indicators',
						// 'display_market_status',
						// 'save_chart_properties_to_local_storage',
						// 'use_localstorage_for_settings',
						// 'adaptive_logo', // 移动端可以隐藏logo
					],
					enabled_features: [
						// 'study_templates',

					],
					//设置成交量默认样式
					studies_overrides: {
						"volume.precision": 0,
						// 销量线
						"volume.volume.color.0": "#fa435b",
						"volume.volume.color.1": "#01eab9",

						"macd.histogram.color.0": "#01eab9",
						"macd.histogram.color.1": "#fa435b",
						"macd.macd.color.0": "#01eab9",
						"macd.signal.color.0": "#fa435b",
					},
					//设置初始化加载条样式
					// loading_screen: {
					// 	"backgroundColor": "#151E25",
					// 	"foregroundColor": "#151E25"
					// },
					// Dark
					theme: 'Dark',
					preset: "mobile",
					//设置初始化样式配置
					overrides: {
						// 蜡烛样式
						"mainSeriesProperties.candleStyle.upColor": "#01eab9",
						"mainSeriesProperties.candleStyle.downColor": "#fa435b",
						// 画布背景颜色
						"paneProperties.background": "#000",
						//纵向网格线颜色
						"paneProperties.vertGridProperties.color": "#000",
						//横向网格线颜色
						"paneProperties.horzGridProperties.color": "#000",
						//标记水印透明度
						"symbolWatermarkProperties.transparency": 0,
						//刻度属性文本颜色
						"scalesProperties.textColor": 'rgba(197, 206, 226, 0.3)',
						// 设置坐标轴字体大小
						//'scalesProperties.fontSize': 16, 
						//隐藏左上角行情信息
						'paneProperties.legendProperties.showLegend': false,
						'left_toolbar': false,
						//销量面板尺寸，支持的值: large, medium, small, tiny
						"volumePaneSize": "medium",
						// 设置十字线
						'paneProperties.crossHairProperties.color': "rgba(197, 206, 226, 0.4)",
						'paneProperties.crossHairProperties.width': 1,
						'paneProperties.crossHairProperties.style': 0,

						//烛心
						"mainSeriesProperties.candleStyle.drawWick": true,
						//烛心颜色
						"mainSeriesProperties.candleStyle.wickUpColor:": '#01eab9',
						"mainSeriesProperties.candleStyle.wickDownColor": "#fa435b",
						//边框
						"mainSeriesProperties.candleStyle.drawBorder": false,
					}
				});
				// console.log(this.widget)
				this.widget && this.widget.onChartReady && this.widget.onChartReady(() => {
					// 这是k线图 展示的 7日均线和30日均线。
					// this.widget.chart().createStudy('Moving Average', false, false, [5], null, {
					// 	'Plot.linewidth': 1,
					// 	'Plot.color': '#f323f7'
					// })
					// this.widget.chart().createStudy('Moving Average', false, false, [10], null, {
					// 	'Plot.linewidth': 1,
					// 	'Plot.color': '#ffe500'
					// })
					// this.widget.chart().createStudy('Moving Average', false, false, [20], null, {
					// 	'Plot.linewidth': 1,
					// 	'Plot.color': '#00fff1'
					// })
					// this.widget.chart().createStudy('MACD', false, false, [12, 26, "close", 9])
					// this.widget.chart().createStudy('Bollinger Bands', false, false)
					// this.widget.chart().createStudy('Stochastic RSI', false, false, [26])
					setTimeout(() => {
						this.widget.chart().resetData()
						this.nowtime();
					}, 200)
				})
				// this.symbol = symbol;
				this.interval = interval;
				// }
			},
			changetype(type) {
				this.widget.chart().setResolution(type)

			},
			tabSelect(item) {
				if (item.id == '666') {
					//指标
					this.setPop = true
				} else {
					this.TabCur = item.id;
					this.scrollLeft = (item.id - 1) * 60
					this.widget.chart().setResolution(item.time)
					this.realtime()
				}
			
			},
			hideb() {
				this.setPop = false
			},
			RadioChange(e) {
				this.radio = e.detail.value
			},
			showModal(name) {
				this.modalName = name
			},
			hideModal(e) {
				this.modalName = null
			},
			RadioChange2(e) {

				// console.log(this.marketList[e.detail.value])
				let info = this.marketList[e.detail.value];
				this.symbol = info.symbol;
				this.salename = info.name;
				this.buyname = info.priceUnit;
				// uni.setNavigationBarTitle({
				// 	title: info.name + '/' + info.priceUnit
				// });
				this.title = info.name + '/' + info.priceUnit + '▼';
				this.radio2 = e.detail.value;
				this.buyfrom.product_id = info.name;
				this.widget.chart().setSymbol(info.symbol)
				this.hideModal();
				setTimeout(() => {
					this.widget.chart().resetData()
					this.nowtime();
				}, 1000)

			},
			nowtime() {

				// Event.off('realTime')
				// 拿到实时数据 在这里画
				Event.on('realTime', data => {
					console.log('realTime-------------------------')
					console.log(data)
					this.high = data.high;
					this.open = data.open;
					this.low = data.low;
					this.close = data.close;
					this.volume = Math.round(data.vol * 100) / 100;
					this.amount = Math.round(data.amount * 100) / 100;
					this.change = Math.round((data.close - data.open) / data.open * 10000) / 100;

					this.id = data.id;

				})
			},
			//加法
			accAdd(arg1, arg2) {
				var r1, r2, m, n;
				try {
					r1 = arg1.toString().split(".")[1].length
				} catch (e) {
					r1 = 0
				}
				try {
					r2 = arg2.toString().split(".")[1].length
				} catch (e) {
					r2 = 0
				}
				m = Math.pow(10, Math.max(r1, r2));
				//last modify by deeka
				//动态控制精度长度
				n = (r1 >= r2) ? r1 : r2;
				var ree = ((arg1 * m + arg2 * m) / m).toFixed(n);
				return ree > 0 ? ree : 0;
			},
			ttt() {

				let b = this.myconfig.q_b[this.salename] ? this.myconfig.q_b[this.salename] : 0.0001;
				let x = Math.cos(Math.PI * Math.round(Math.random()));
				let y = x * Math.random() * b;
				let z = this.accAdd(this.close, y);
				let nn = Math.round(z * 10000) / 10000;

				let newdata = {
					amount: 2.0624879444902167,
					close: nn,
					count: 80,
					high: this.high,
					id: this.id,
					low: this.low,
					open: this.open,
					vol: 0
				}

				Event.emit('realTime', newdata)

			},
			realtime() {
				setTimeout(() => {
					this.nowtime();
				}, 1000)

			},
			onClick(type) {
				// let data = {
				// 	symbol: this.symbol,
				// 	name: this.salename,
				// 	priceUnit: this.buyname,
				// 	type: type
				// }
				// uni.setStorageSync('market', data)
				uni.switchTab({
					url: `/pages/contract/main`
				})
			},
			gobuy(type) {
				if (!this.hasLogin) {
					this.$api.msg(this.i18n.popup.loginfirst)
					return false;
				}
				if (this.buyfrom.hand == 0) {
					this.$api.msg(this.i18n.kline.inputmoney)
					return false;
				}
				if (!this.close) {
					this.$api.msg(this.i18n.popup.slow)
					return false;
				}
				this.buyfrom.rise_fall = type;
				this.buyfrom.time = this.radio;
				this.buyfrom.price = this.close;
				// if (this.buyfrom.num * this.buyfrom.price < this.rule.trade_min) {
				// 	this.$api.msg('最小交易金额为' + this.rule.trade_min)
				// 	return false;
				// }

				uni.showModal({
					title: this.i18n.popup.tips,
					content: this.i18n.popup.confirm2,
					cancelText: this.i18n.popup.cancel,
					confirmText: this.i18n.popup.confirm,
					confirmColor: '#000000',
					success: (e) => {
						if (e.confirm) {
							// this.$http.post('btc.binfo', this.buyfrom).then(info => {
							// this.buyfrom.price = info.data[this.salename].price;
							this.$http.post('Qi.submit', this.buyfrom).then(res => {
								console.log(res)
								if (res.msg) {
									this.$api.msg(res.msg)
								}
								this.getUserinfo();
								this.$refs.child.loadNewsList('refresh'); //刷新委托列表
								this.buyfrom.hand = '';
							})
							// })
						}
					}
				});

			},
			BackPage() {
				uni.navigateBack({
					delta: 1
				});
			},
			chose() {
				this.buyfrom.sim = this.buyfrom.sim == 1 ? '2' : '1';
			},
			setb(name) {
				this.zhibiao = name
				switch (name) {
					case 'BOLL':
						this.widget.chart().createStudy('Bollinger Bands', false, false)
						break;
					case 'MACD':
						this.widget.chart().createStudy('MACD', false, false, [12, 26, "close", 9])
						break;
					case 'RSI':
						this.widget.chart().createStudy('Stochastic RSI', false, false, [26])
						break;
					case '5MA':
						this.widget.chart().createStudy('Moving Average', false, false, [5], null, {
							'Plot.linewidth': 3,
							'Plot.color': '#e64bf5'
						})
						break;
					case '10MA':
						this.widget.chart().createStudy('Moving Average', false, false, [10], null, {
							'Plot.linewidth': 3,
							'Plot.color': '#ffc07b'
						})
						break;
					case '20MA':
						this.widget.chart().createStudy('Moving Average', false, false, [20], null, {
							'Plot.linewidth': 3,
							'Plot.color': '#51d2ff'
						})
						break;
				}
			},
			
		}
	};
</script>

<style lang="scss">
	#trade-view {
		width: 100%;
		height: 56vh;
	}

	iframe {
		width: 100%;
		height: 100% !important;
	}

	.pane-legend-line.pane-legend-wrap.main.expand-line {
		padding-right: 5px;
	}

	.row {
		display: inline;
	}


	.dibu {
		padding: 10px 5px;
		bottom: 0px;
		position: absolute;
		width: 100%;
	}

	.dbt {
		width: 94%;
		margin: 0 auto;
		height: 43px;
	}

	.inin {
		height: 32px;
		display: flex;
		-webkit-box-align: center;
		align-items: center;
		border-radius: 20px;
		background-color: #f7f8f9;
		padding: 0 22px;
		margin-bottom: 0px;
	}

	.toptext {
		font-size: 10px;
	}

	.tit {
		/* color: #FFFFFF; */
		font-size: 10px;
	}

	.tit2 {
		color: #AEAEAE;
		font-size: 10px;
	}

	.big-txt {
		font-size: x-large;
		font-weight: 600;
	}
	.set-box {
		position: absolute;
		width: 100%;
		background-color: #000;
		font-size: 15px;
	
		.item {
			height: 100rpx;
			line-height: 48rpx;
			font-size: 32rpx;
			color: rgba($color: #fff, $alpha: 0.5);
			/* 根据实际情况修改 */
			justify-content: space-between;
	
			text {
				padding: 0 20rpx;
			}
	
			.title {
				text-align: center;
				display: block;
				border-right: 1rpx solid #f1f1f1;
				min-width: 120rpx;
			}
	
			scroll-view {
				width: 500rpx;
				white-space: nowrap;
	
				view {
					display: inline-block;
				}
	
				.active {
					color: #fff;
				}
			}
	
	
			.right {
				padding: 10rpx 20rpx;
			}
		}
	}
</style>
